import {defineStore} from "pinia"
import {http} from "../axios/index.js"
import {useWidgetStore} from "./widget.js"

export const useUserStore = defineStore("user",{
    //用户状态
    state: ()=>({
        userInfo: {}
    }),
    getters: {
        //登录状态
        isLogin(){
            return !!this.userInfo.uid
        },
        //字体颜色
        color(){
            return this.userInfo.color || "#000000"
        },
        //背景颜色
        bg(){
            return this.userInfo.bg || "#ffffff"
        },
        //激活状态颜色
        primary(){
            return this.userInfo.primary || "#09c"
        }
    },
    actions: {
        //登录
        async login(user){
            const res = await http({
                method: "POST",
                data: user,
                url: "user/login"
            })
            if(res.data.code === 0){
                this.userInfo = res.data.data.userInfo
                sessionStorage.setItem("masterwork",JSON.stringify(res.data.data.userInfo))
                const widgetStore = useWidgetStore()
                await widgetStore.toggleWidget(this.userInfo.wid)
                return true
            }else{
                return false
            }
        },
        //退出
        logout(){
            this.userInfo = {}
            sessionStorage.removeItem("masterwork")
        },
        //初始化
        async init(){
            const userInfo = sessionStorage.getItem("masterwork")
            this.userInfo = userInfo ? JSON.parse(userInfo) : {}
            if(this.login){
                const widgetStore = useWidgetStore()
                await widgetStore.toggleWidget(this.userInfo.wid)
            }
        }
    }
})